#include "workCmd.h"

int recvn(int sockfd, void *buf, int length){
    int total = 0;
    char *p = (char *)buf;
    while(total < length){
        ssize_t sret = recv(sockfd,p+total,length-total,0);
        total += sret;
    }
    return total;
}

int sendFile(int netFd,char *file){
    train_t train;
    train.length = strlen(file);
    memcpy(train.data,file,train.length);
    printf("%d ,%s\n",train.length,train.data);
    send(netFd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    send(netFd,train.data,train.length,MSG_NOSIGNAL);

    int fd = open(file,O_RDWR);
    struct stat statbuf;
    fstat(fd,&statbuf);
    off_t filesize = statbuf.st_size;
    train.length = sizeof(filesize);
    memcpy(train.data,&filesize,train.length);
    send(netFd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
    send(netFd,train.data,train.length,MSG_NOSIGNAL);

    printf("Filesize = %ld\n",filesize);
    //小文件秒传，大文件小火车传
    if(filesize < 4096){
        printf("Tiny file.\n");
        char *p = (char *)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
        send(netFd,p,filesize,MSG_NOSIGNAL);
        munmap(p,filesize);
    }
    else{
        printf("Hurge file~\n");
        while(1){
            bzero(train.data,sizeof(train.data));
            ssize_t ret = read(fd,train.data,sizeof(train.data));
            train.length = ret;
            send(netFd,&train.length,sizeof(train.length),MSG_NOSIGNAL);
            send(netFd,train.data,train.length,MSG_NOSIGNAL);
            if(ret == 0){
                break;
            }
        }
    }
    close(fd);
    return 0;
}

//recvn封装版本，强制recv完，进度条
//小文件秒传，大文件慢慢传
int recvFile(int netfd){
    train_t train;
    char filename[4096] = {0};
    recvn(netfd,&train.length,sizeof(train.length));//收火车头
    recvn(netfd,train.data,train.length);//收车厢
    memcpy(filename,train.data,train.length);
    printf("%s\n",filename);

    int fd = open(filename,O_RDWR|O_CREAT|O_TRUNC,0666);
    ERROR_CHECK(fd,-1,"open");

    off_t filesize = 0;
    recvn(netfd,&train.length,sizeof(train.length));
    recvn(netfd,train.data,train.length);
    memcpy(&filesize,train.data,train.length);

    printf("Filesize = %ld\n",filesize);
    if(filesize < 4096){
        printf("Tiny file.\n");
        ftruncate(fd,filesize);
        char *p = (char *)mmap(NULL,filesize,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
        recvn(netfd,p,filesize);
        munmap(p,filesize);
    }
    else{
        printf("Hurge file~\n");
        off_t currsize = 0;
        while(1){
            recvn(netfd,&train.length,sizeof(train.length));//收火车头
            if(train.length == 0){
                break;
            }
            currsize += train.length;
            printf("%5.2lf%%\r",100.0*currsize/filesize);
            fflush(stdout);

            sleep(1);
            recvn(netfd,train.data,train.length);//收车厢
            write(fd,train.data,train.length);
        }
    }
    printf("100.00%%\n");
    close(fd);
    return 0;
}

